package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.entity.Role;
import com.qk.entity.dto.role.RoleDTO;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author fantuan
 * @created 2025/10/8 11:42
 * @description
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<Role> list() {
        return roleMapper.list();
    }

    @Override
    public PageResult<Role> page(RoleDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Role> result = roleMapper.selectByPage(dto);
        Page<Role> page = (Page<Role>) result;
        return PageResult.<Role>builder()
                .total((int) page.getTotal())
                .rows(result)
                .build();

    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteById(id);
    }

    @Override
    public void add(Role role) {
        boolean hasNull = BeanUtil.hasNullField(role,"id","remark","createTime","updateTime");
        if(hasNull){
            throw new RuntimeException("参数错误");
        }
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.add(role);
    }

    @Override
    public Role getRoleById(Integer id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public void update(Role role) {
        boolean hasNull = BeanUtil.hasNullField(role,"id","remark","createTime","updateTime");
        if(hasNull){
            throw new RuntimeException("参数错误");
        }
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
    }
}
